﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Text;
using FeaturePlusInWeb.Model;
using System.Windows.Browser;
using System.Json;

namespace FeaturePlusInWeb.Control
{
    public partial class CreateEditFPlus : ChildWindow
    {
        private CreateEditFPlus()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 模版的上级ID或者模版ID
        /// </summary>
        public int Fid
        {
            get;
            set;
        }

        /// <summary>
        /// 是否是创建新模版
        /// </summary>
        public bool IsCreate
        {
            get;
            set;
        }

        /// <summary>
        /// 上一级的唯一标识符，只用于创建推荐位的时候，继承上级的唯一标识符（形式:   index_tuijianwei_aaaaa_bbbb）
        /// </summary>
        public string FKeyName
        {
            get;
            set;
        }

        public CreateEditFPlus(int fid,bool isCreate):this()
        {
            IsCreate = isCreate;
            Fid = fid;

            if (isCreate)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("{dede:php}");
                sb.AppendLine("    foreach($data as $d)");
                sb.AppendLine("    {");
                sb.AppendLine("    //注意：模版暂时不能使用转义符\\，请使用单引号方式代替");
                sb.AppendLine("        echo \"<a href='\".$d->UrlLink.\"'><img src='\".$d->PicLink.\"'/></a>\";");
                sb.AppendLine("        echo \"<a href='\".$d->UrlLink.\"'>\".$d->Title.\"</a>\";");
                sb.AppendLine("        echo $d->Id;");
                sb.AppendLine("        echo $d->Title;");
                sb.AppendLine("    }");
                sb.AppendLine("{/dede:php}");
                txtTemplete.Text = sb.ToString();

                txtDatatype.SelectedIndex = 0;
                label5.Content = "模版：";
            }
            else
            {
                //绑定需要修改的数据。
                //view-source:http://127.0.0.1:8081//featuredplus/getFeaturePlustTree.php?id=13
                string url = Config.UrlHead + "/featuredplus/getFeaturePlustTree.php?searchtype=id&id=" + fid + Config.UrlEnd;

                WebClient webGet = new WebClient();
                webGet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webGet_DownloadStringCompleted);
                webGet.DownloadStringAsync(new Uri(url));
            }
        }

        void webGet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != "")
            {
                var jsonValue = JsonValue.Parse(e.Result);

                var model = ObjectReflactor.PopulateEntityFromCollection<FeaturedPlusTemplet>(jsonValue);

                txtDatamaxsize.Value = model.Datamaxsize;

                //((ComboBoxItem)txtDatatype.SelectedItem).DataContext = model.Datatype;

                int i = 0;

                foreach(ComboBoxItem cbi in txtDatatype.Items)
                {

                    if (cbi.DataContext.ToString() == model.Datatype)
                    {
                        txtDatatype.SelectedIndex = i;
                    }
                    i++;
                }

                txtDescription.Text = model.Description;
                txtKeyname.Text = model.Keyname;
                txtName.Text = model.Name;

                //如果是静态块，也是显示模版（静态块的模版就是块本身）
                if (model.Datatype == Config.SearchType.StaticBlock.ToString())
                {
                    txtTemplete.Text = HttpUtility.HtmlDecode(model.Htmlshow);
                    label5.Content = "静态块：";
                }
                else
                {
                    txtTemplete.Text = HttpUtility.HtmlDecode(model.Templete);
                    label5.Content = "模版：";
                }
                //txtTitlemaxsize.Value = -1;
                txtSingpic.Text = model.Signpic;
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            FeaturedPlusTemplet templet = new FeaturedPlusTemplet();

            templet.Datamaxsize = (int)txtDatamaxsize.Value;

            templet.Description = txtDescription.Text;
            templet.Fid = Fid;
            templet.Htmlshow = "";
            templet.Keyname = ((FKeyName == string.Empty) ? "" : FKeyName + "_") + txtKeyname.Text;
            templet.Name = txtName.Text;

            if (templet.Keyname == "")
            {
                MessageBox.Show("唯一标识符不能为空！");
                txtKeyname.Focus();
                return;
            }

            if (templet.Name == "")
            {
                MessageBox.Show("推荐位名称不能为空！");
                txtName.Focus();
                return;
            }

            var templeteDataType = ((ComboBoxItem)txtDatatype.SelectedItem).DataContext.ToString();

            templet.Datatype = templeteDataType;

            if (templeteDataType == Config.SearchType.StaticBlock.ToString())
            {
                if (txtTemplete.Text == "")
                {
                    MessageBox.Show("静态块内容不能为空！");
                    return;
                }
                else
                {
                    templet.Htmlshow = HttpUtility.HtmlEncode(txtTemplete.Text);//静态块
                }
            }
            else
            {
                //除了静态块，都有模版（目录的模版是空的，所以不影响）
                templet.Templete = HttpUtility.HtmlEncode(txtTemplete.Text);
            }

            templet.Titlemaxsize = -1;
            templet.Lastupdatetime = DateTime.Now;
            templet.Signpic = txtSingpic.Text;

            //修改时要给主键赋值
            if (!IsCreate)
            {
                templet.Id = Fid;
            }

            var data = Newtonsoft.Json.JsonConvert.SerializeObject(templet);

            string url = Config.UrlHead + "/featuredplus/upFeaturedPlusTemplet.php?uptype=" + (IsCreate ? "i" : "u") + Config.UrlEnd;

            WebClient cep = new WebClient();
            cep.UploadStringCompleted += new UploadStringCompletedEventHandler(cep_UploadStringCompleted);
            cep.UploadStringAsync(new Uri(url), "POST", data);
        }

        void cep_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            if (e.Result == "ok")
            {
                this.DialogResult = true;
            }
            else
            {
                //txtDescription.Text = e.Result;
                MessageBox.Show(e.Result);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void txtDatatype_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (txtDatatype != null && txtDatatype.SelectedItem != null)
            {

                var templeteDataType = ((ComboBoxItem)txtDatatype.SelectedItem).DataContext.ToString();


                if (templeteDataType == Config.SearchType.IsRoof.ToString())
                {
                    IsRoofhas.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    IsRoofhas.Visibility = System.Windows.Visibility.Visible;
                }
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            UploadImage u = new UploadImage();
            u.Closed += new EventHandler(u_Closed);
            u.Show();
        }

        void u_Closed(object sender, EventArgs e)
        {
            var uu = ((UploadImage)(sender));

            if (uu.DialogResult == true)
            {
                txtSingpic.Text = uu.ImgUrl;
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

